package com.example.musicplayer.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.musicplayer.R
import com.example.musicplayer.adapter.MusicAdapter.MusicViewHolder
import com.example.musicplayer.model.Music

/**
 * 音乐列表适配器
 */
class MusicAdapter(private val musicList: List<Music>, private val listener: OnMusicClickListener) :
    RecyclerView.Adapter<MusicViewHolder>() {
    interface OnMusicClickListener {
        fun onMusicClick(music: Music?)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MusicViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.music_item, parent, false)
        return MusicViewHolder(view)
    }

    override fun onBindViewHolder(holder: MusicViewHolder, position: Int) {
        val music = musicList[position]

        holder.titleTextView.text = music.title
        holder.singerTextView.text = music.singer

        Glide.with(holder.itemView.context)
            .load(music.coverImgUrl) // 封面图片的 URL
            .placeholder(R.drawable.ic_launcher_background) // 占位图
            .error(R.drawable.ic_launcher_background) // 加载失败时的图片
            .into(holder.coverImageView)
        holder.itemView.setOnClickListener { listener.onMusicClick(music) }
    }

    override fun getItemCount(): Int {
        return musicList.size
    }

    class MusicViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var titleTextView: TextView
        var singerTextView: TextView
        var coverImageView: ImageView

        init {
            titleTextView = itemView.findViewById(R.id.music_title)
            singerTextView = itemView.findViewById(R.id.music_singer)
            coverImageView = itemView.findViewById(R.id.music_cover)
        }
    }
}